<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      background-color: black;
    }
    .ball {
      position: absolute;
      border-radius: 50%;
    }
  </style>
</head>
<body>
  <script>
    function Ball(x,y){
      // 属性x，y表示的是圆心的坐标
      this.x = x;
      this.y = y;
      // 小球半径
      this.r = 20;
      // 透明度
      this.opacity = 1;
      // 小球背景演唱
      this.color = colorArr[parseInt(Math.random() * colorArr.length)];
      // 这个小球的x增量和y增量,使用do while 语句来防止dx和dy同时为0
      do {
        this.dx = parseInt(Math.random() * 15) -5;
        this.dy = parseInt(Math.random() * 15) -5;
      }while(this.dx == 0 && this.dy == 0);
      // 初始化
      this.init();
      ballArr.push(this);
      //this.update();
    }
    Ball.prototype.init = function(){
      this.dom = document.createElement('div');
      this.dom.className = 'ball';
      this.dom.style.width = this.r * 2 + 'px';
      this.dom.style.height = this.r * 2 + 'px';
      this.dom.style.left = this.x - this.r + 'px';
      this.dom.style.top = this.y -this.r + 'px'
      this.dom.style.backgroundColor = this.color;
      document.body.appendChild(this.dom);
    }
    // 更新
    Ball.prototype.update = function(){
      // 位置改变
      this.x += this.dx;
      this.y -= this.dy;
      // 半径改变
      this.r += 0.2;
      // 透明度改变
      this.opacity -= 0.02;
      this.dom.style.width = this.r * 2 + 'px';
      this.dom.style.height = this.r * 2 + 'px';
      this.dom.style.left = this.x - this.r + 'px';
      this.dom.style.top = this.y -this.r + 'px'
      this.dom.style.opacity = this.opacity;
      // 当透明度小于0 的时候，就需要从数组中删除自己，DOM元素也要删除自己
      if (this.opacity < 0) {
        for(var i = 0;i < ballArr.length;i++){
          if(ballArr[i] == this){
              ballArr.splice(i,1)
          }
        }
        // 还要删除自己的dom
        document.body.removeChild(this.dom);
      }
    }
 
    var ballArr = [];
    // 初始化颜色数组
    var colorArr = ['#66CCCC','#CCFF66','#FF99CC','#FF6666','#CC3399','#FF6600'];
    
   
    setInterval(() => {
      // 遍历数组
      for(var i = 0; i < ballArr.length;i++){
        ballArr[i].update();
      }
    }, 20);

    document.onmousemove = function(e){
      var x = e.clientX
      var y = e.clientY
      new Ball(x,y);
    }
  </script>
</body>
</html>